<template>
  <div>
    <el-form
    ref="form"
    :rules="rules"
    :model="role"
    label-width="100px"
    label-position="right"
    >
    <el-form-item prop="name" label="角色名称:">
        <el-input v-model="role.name" size="mini"></el-input>
    </el-form-item>
    <el-form-item prop="code" label="角色编码:">
        <el-input v-model="role.code" size="mini"></el-input>
    </el-form-item>
    <el-form-item prop="description" label="描述:">
        <el-input type="textarea" v-model="role.description"></el-input>
    </el-form-item>
    <el-form-item class="btn">
        <el-button @click="$emit('cancel')">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
    </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { Form } from 'element-ui'
import { createOrUpdateRole, getRoleById } from '@/services/role'

export default Vue.extend({
  name: 'CreateOrEdit',
  props: {
    roleId: {
      type: [String, Number]
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  created () {
    // 如果是编辑操作，根据角色id加载信息
    if (this.isEdit) {
      this.loadRole()
    }
  },
  data () {
    return {
      role: {
        code: '',
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入角色编码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async onSubmit () {
      try {
        // 验证
        await (this.$refs.form as Form).validate()
        await createOrUpdateRole(this.role)
        this.$message.success(`${this.isEdit ? '保存' : '添加'}角色成功`)
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    async loadRole () {
      const { data } = await getRoleById(this.roleId)
      this.role = data.data
    }
  }
})
</script>

<style lang="scss" scoped>
.btn {
    display: flex;
    justify-content: center;
}
</style>
